import { getToken } from '@/utils/auth'
import { updateCompanySelfAss, companySelfDetail } from '@/api/company_self_ass'
import { getFileType, isImage, isMsOfficeFile } from '@/utils/index'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'CompanyForm',
  components: { ElImageViewer },
  data() {
    return {
      loading: false,
      loadingText: '',
      self_upload_limit: 1,
      category_1_limit: 1,
      uploadUrl: process.env.VUE_APP_BASE_API + 'api/company_self_assessment/upload_file/',
      selfAssessmentTable: [],
      fileList: {
        category_1_f: {
          'category_1_1': [],
          'category_1_2': [],
          'category_1_3': []
        },
        category_2_f: {
          'category_2_1': [],
          'category_2_2': [],
          'category_2_3': [],
          'category_2_4': [],
          'category_2_5': []
        },
        category_3_f: {
          'category_3_1': [],
          'category_3_2': [],
          'category_3_3': [],
          'category_3_4': []
        },
        category_4_f: {
          'category_4_1': [],
          'category_4_2': [],
          'category_4_3': [],
          'category_4_4': [],
          'category_4_5': [],
          'category_4_6': [],
          'category_4_7': []
        },
        category_5_f: {
          'category_5_1': [],
          'category_5_2': []
        },
        category_6_f: {
          'category_6_1': [],
          'category_6_2': []
        },
        category_7_f: {
          'category_7_1': [],
          'category_7_2': [],
          'category_7_3': []
        },
        category_8_f: {
          'category_8_1': []
        }
      },
      form: {
        company_name: '',
        address: '',
        people_name: '',
        telephone: '',
        self_assessment_table: [],
        category_1: {
          'category_1_1': [],
          'category_1_2': [],
          'category_1_3': []
        },
        category_2: {
          'category_2_1': [],
          'category_2_2': [],
          'category_2_3': [],
          'category_2_4': [],
          'category_2_5': []
        },
        category_3: {
          'category_3_1': [],
          'category_3_2': [],
          'category_3_3': [],
          'category_3_4': []
        },
        category_4: {
          'category_4_1': [],
          'category_4_2': [],
          'category_4_3': [],
          'category_4_4': [],
          'category_4_5': [],
          'category_4_6': [],
          'category_4_7': []
        },
        category_5: {
          'category_5_1': [],
          'category_5_2': []
        },
        category_6: {
          'category_6_1': [],
          'category_6_2': []
        },
        category_7: {
          'category_7_1': [],
          'category_7_2': [],
          'category_7_3': []
        },
        category_8: {
          'category_8_1': []
        }
      },
      rules: {
        company_name: [
          { required: true, message: '该项为必填项', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '该项为必填项', trigger: 'blur' }
        ],
        people_name: [
          { required: true, message: '该项为必填项', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '该项为必填项', trigger: 'blur' }
        ],
        self_assessment_table: [
          { required: true, message: '必须上传自评表', trigger: 'change' }
        ]
      },
      submitType: 'create',
      id: undefined,
      imgUrl: '',
      previewImg: false
    }
  },
  watch: {
  },
  created() {
    this.form.company_name = this.$store.getters.name
    // if (this.$store.getters.ying_ji) {
    //   this.rules['category_5_1'] = [
    //     { required: true, message: '文件必须上传', trigger: 'change' }
    //   ]
    //   this.rules['category_5_2'] = [
    //     { required: true, message: '文件必须上传', trigger: 'change' }
    //   ]
    // }
    // if (this.$store.getters.jian_kong) {
    //   this.rules['category_6_1'] = [
    //     { required: true, message: '文件必须上传', trigger: 'change' }
    //   ]
    //   this.rules['category_6_2'] = [
    //     { required: true, message: '文件必须上传', trigger: 'change' }
    //   ]
    // }
    this.id = this.$route.query.id
    if (this.id) {
      const loading = this.$loading({
        lock: true,
        text: '正在获取数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      companySelfDetail(this.id).then(res => {
        loading.close()
        this.form = res
        this.fileList = res
        this.selfAssessmentTable = res.self_assessment_table_f
      }).catch((error) => {
        this.$message.error(error.response.data.message)
      })
    }
  },
  computed: {
    headers: function() {
      return { Authorization: 'Bearer ' + getToken() }
    }

  },
  methods: {
    // 提交表单
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          updateCompanySelfAss(this.id, this.form).then(response => {
            loading.close()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            if (this.$store.getters.ying_ji) {
              if (this.form.category_5.category_5_1.length === 0 || this.form.category_5.category_5_2.length === 0) {
                const message = '您有指标五的文件尚未上传。'
                this.$message.warning(message)
              }
            }
            if (this.$store.getters.jian_kong) {
              if (this.form.category_6.category_6_1.length === 0 || this.form.category_6.category_6_2.length === 0) {
                const message = '您有指标六的文件尚未上传。'
                this.$message.warning(message)
              }
            }
            this.$router.push({
              name: 'CompanySelfList'
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          this.$message.error('有必填项没填，或者填写错误，请检查表单。')
        }
      })
    },

    // 上传文件之前的钩子
    beforeUpload(file) {
      // 限制文件上传大小, 大于1M则提示, 且不请求提交表单
      const flag = file.size / 1024 / 1024 < 30
      if (!flag) {
        this.$message.error('上传文件大小不能超过30M')
        return false
      }
    },
    // 上传文件数量超出自定义数量
    handleExceed(files, fileList) {
      this.$message.warning('当前限制选择 1 个文件, 请删除后继续上传')
    },
    handleProgress(event, file, fileList) {
      this.loading = true
      this.loadingText = '正在上传文件....'
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      // 上传成功后，手动验证一次表单
      this.loading = false
      this.$message({
        message: '上传文件成功',
        type: 'success'
      })
      this.form.self_assessment_table.push(response.data)
      this.$refs.form.validateField('self_assessment_table')
    },
    // 上传失败
    handleError(res_error, file, fileList) {
      this.loading = false
      this.$message({
        message: '上传文件失败',
        type: 'danger'
      })
    },
    // 文件列表移除文件
    handleRemove(file, fileList) {
      console.log(file)
      let filename = ''
      if (file.response) {
        filename = file.response.data
      } else {
        filename = 'self_assessment/' + file.name
      }
      for (var i = 0; i < this.form.self_assessment_table.length; i++) {
        if (filename === this.form.self_assessment_table[i]) {
          this.form.self_assessment_table.splice(i, 1)
          break
        }
      }
    },

    // 指标的
    handleSuccess1(response, key1, key2) {
      this.loading = false
      this.$message({
        message: '上传文件成功',
        type: 'success'
      })
      this.form[key1][key2].push(response.data)
      this.$refs.form.validateField(key2)
      console.log(this.form)
    },
    handleRemove1(file, key1, key2) {
      let filename = ''
      if (file.response) {
        filename = file.response.data
      } else {
        filename = key1 + '/' + file.name
      }
      for (var i = 0; i < this.form[key1][key2].length; i++) {
        if (filename === this.form[key1][key2][i]) {
          this.form[key1][key2].splice(i, 1)
          break
        }
      }
      console.log(this.form)
    },
    // 文件在线预览
    onlineRead(file) {
      const url = file.url
      const fileType = getFileType(url)
      if (isMsOfficeFile(fileType)) {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + url)
      } else if (isImage(fileType)) {
        this.imgUrl = url
        console.log(this.imgUrl)
        this.previewImg = true
      } else {
        window.open(url)
      }
    },
    // 关闭预览图片
    closePreviewImage() {
      this.previewImg = false
    }

  }
}
